#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QTextStream>

void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString txt;
    switch (type) {
    //调试信息提示
    case QtDebugMsg:
        txt = QString("Debug: %1").arg(msg);
        break;

        //一般的warning提示
    case QtWarningMsg:
        txt = QString("Warning: %1").arg(msg);
        break;
        //严重错误提示
    case QtCriticalMsg:
        txt = QString("Critical: %1").arg(msg);
        break;
        //致命错误提示
    case QtFatalMsg:
        txt = QString("Fatal: %1").arg(msg);
    }

    QFile outFile("debuglog.txt");
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&outFile);
    ts <<context.file<<":"<<context.line<<"-fun-"<<context.function<<txt << endl;

    if (type == QtFatalMsg) {
        abort();    /*这里程序异常退出*/
    }
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //先注册自己的MsgHandler
    qInstallMessageHandler(customMessageHandler);

    //以后就可以像下面这样直接打日志到文件中，而且日志也会包含时间信息
    qDebug("This is a debug message, Hello %s", "jake");
    qWarning("This is a warning message!!");
    qCritical("This is a critical message!");
    qFatal("This is a fatal message!!");

    return a.exec();
}

